/*
** execute.c for 42sh in /home/demesy_j/svn/quarante-deuxsh/trunk
** 
** Made by julien demesy
** Login   <demesy_j@epitech.net>
** 
** Started on  Tue Mar 13 18:27:30 2012 julien demesy
** Last update Thu Mar 15 15:26:46 2012 julien demesy
*/

#include	<unistd.h>
#include	<stdlib.h>
#include	<stdio.h>
#include	<errno.h>
#include	<signal.h>
#include	<sys/types.h>
#include	<sys/wait.h>
#include	<string.h>
#include	"list.h"
#include	"builtins.h"
#include	"parse.h"

char		*my_strcat(char *s1, char *s2)
{
  char		*ns;
  int		i;
  int		j;

  ns = malloc((strlen(s1) + strlen(s2) + 1) * sizeof(*ns));
  i = 0;
  j = 0;
  while (s1[j])
    ns[i++] = s1[j++];
  j = 0;
  while (s2[j])
    ns[i++] = s2[j++];
  ns[i] = '\0';
  return (ns);
}

char		*compose_cmd(t_list *path, char **argtab)
{
  t_list	*it;

  it = path->next;
  while (it != path)
    {
      if (access(my_strcat(my_strcat(it->data,"/"), argtab[0]), F_OK) != -1)
	return (my_strcat(my_strcat(it->data,"/"), argtab[0]));
      else
	it = it->next;
    }
  return (NULL);
}

void		correct_arglist(char **arglist, char *str)
{
  if (str)
    {
      arglist[0] = malloc(strlen(str) * sizeof(char));
      arglist[0] = str;
    }
}

int		check_builtins(char **arglist, t_list *env)
{
  if (strcmp(arglist[0], "env") == 0)
    {
      my_env(env);
      return (1);
    }
  else if (strcmp(arglist[0], "exit") == 0)
    exit(EXIT_SUCCESS);
  else if (strcmp(arglist[0], "unsetenv") == 0)
    {
      my_unsetenv(env, arglist[1]);
      return (1);
    }
  else if (strcmp(arglist[0], "setenv") == 0)
    {
      my_setenv(env, arglist[1]);
      return (1);
    }
  else if (strcmp(arglist[0], "cd") == 0)
    {
      my_cd(env, arglist[1]);
      return (1);
    }
  return (0);
}

int		execute(char **arglist, t_list *env)
{
  int		status;
  int		pid;

  if (check_builtins(arglist, env) == 0)
    {
      correct_arglist(arglist, compose_cmd(create_path_list(env), arglist));
      pid = fork();
      if (pid != 0)
	{
	  pid = wait(&status);
	  return (pid);
	}
      else
	{
	  signal(SIGINT, SIG_DFL);
	  execve(arglist[0], arglist, get_env_tab(env));
	  puts(strerror(errno));
	  exit(-1);
	}
    }
  return (0);
}
